<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" draggable>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px" @keyup.enter="submitHandle()">
      <el-form-item label="专业" prop="specializedId">
        <el-select v-model="dataForm.specializedId">
          <el-option v-for="item in speList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
			<el-form-item label="年级" prop="grade">
				<el-input v-model="dataForm.grade"></el-input>
			</el-form-item>
      <el-form-item label="班号" prop="lv">
				<el-input-number v-model="dataForm.lv" placeholder="填写几班" :min="1"></el-input-number>
			</el-form-item>
      <el-form-item label="辅导员" prop="teacherId">
				<el-select v-model="dataForm.teacherId">
          <el-option v-for="item in teacherList" :label="item.name" :value="item.id" :key="item.id"/>
        </el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import {useSpeSelectApi} from "@/api/college/spe";
import {useClassSubmitApi} from "@/api/college/class";
import {useTeacherListApi} from "@/api/college/teacher";

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()
const speList = ref<any[]>([])
const teacherList = ref<any[]>([])

const dataForm = reactive({
	id: '',
  lv: 1,
  grade: new Date().getFullYear(),
  specializedId: "",
  teacherId: ""
})

const init = (data: any) => {
	visible.value = true
	dataForm.id = ''
  dataFormRef.value?.resetFields()

	// 存在则为修改
	if (data?.id) {
    Object.assign(dataForm, data)
	}
  getSpeList()
  getTeacherList()
}

const dataRules = ref({
  lv: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  grade: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  specializedId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  teacherId: { required: true, message: '必填项不能为空', trigger: 'blur' }
})

function getSpeList(){
  useSpeSelectApi().then(res=>{
    speList.value = res.data
  })
}
function getTeacherList(){
  useTeacherListApi().then(res=>{
    teacherList.value = res.data
  })
}
// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
    useClassSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
